/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.zt.dangyuan;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import io.zt.dangyuan.customView.OnRefreshListener;
import io.zt.dangyuan.customView.RefreshListView;
import io.zt.dangyuan.object.ContentListObject;
import io.zt.dangyuan.object.ContentListRequest;


public class MyFragment0 extends Fragment implements OnRefreshListener {


    @InjectView(R.id.mmlist)
    RefreshListView recyclerview;
    private List<ContentListObject.ListEntity> datas;
    private BBSItemAdapter1 adapter;
    private int type;
    ContentListRequest contentListRequest;

    private String cid;
    private int pos;

    public void setPos(int pos) {
        this.pos = pos;
    }

    public void setCid(String cid) {
        this.cid = cid;
    }


    Handler dataHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            Toast.makeText(getActivity(), "已经没有更多数据了，亲", Toast.LENGTH_SHORT).show();
            if (msg.what == 0) {
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(
                R.layout.fragment_only_recyclerview, container, false);
        ButterKnife.inject(this, v);
        initDatas();
        return v;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

    }

    @Override
    public void onStart() {
        super.onStart();

    }

    public void initDatas() {

        datas = new ArrayList<ContentListObject.ListEntity>();
        contentListRequest = new ContentListRequest();
        contentListRequest.setPageSize("10");
        contentListRequest.setTapType("1");

        adapter = new BBSItemAdapter1(getActivity(), datas);
        recyclerview.setAdapter(adapter);
        recyclerview.setOnRefreshListener(this);
        recyclerview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    return;
                }
                Intent intent = new Intent(getActivity(), BBSDetailActivity.class);
                ContentListObject.ListEntity object = datas.get(position - 1);

                intent.putExtra("contentid", object.getArcId());
                intent.putExtra("type", pos);
                intent.putExtra("cid", cid);
                intent.putExtra("commotcount", object.getComments());
                startActivity(intent);
            }
        });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);

    }

    @Override
    public void onDownPullRefresh() {
        contentListRequest.setTapType("1");
//            webRequst(false);
        downPullRefresh();
    }

    @Override
    public void onLoadingMore() {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                contentListRequest.setTapType("2");
                webRequst(false);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (recyclerview != null)
                    recyclerview.hideFooterView();
            }
        }.execute(new Void[]{});
    }

    public static MyFragment0 newInstance(int type) {
        MyFragment0 tabFragment = new MyFragment0();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        tabFragment.setArguments(bundle);
        return tabFragment;
    }

    public static MyFragment0 newInstance(int type, String cid) {
        MyFragment0 tabFragment = new MyFragment0();
        Bundle bundle = new Bundle();

        bundle.putInt("type", type);
        tabFragment.setArguments(bundle);
        return tabFragment;
    }


    private int getType() {
        Bundle bundle = this.getArguments();
        return bundle.getInt("type", BBSDetailActivity.TYPE_ZHONGCHOU);
    }

    /************
     * 生活服务页面参数
     ***********/
    private String title;
    private int iconId;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getIconId() {
        return iconId;
    }

    public void setIconId(int iconId) {
        this.iconId = iconId;
    }


    public void webRequst(Boolean isShow) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("taptype", contentListRequest.getArcType());
        map.put("pagesize", String.valueOf(Constant.page));
        if (contentListRequest.getTapType().equals("1")) {
//            map.put("criticalId", contentListRequest.getArcType());
        } else {
            ContentListObject.ListEntity object = datas.get(datas.size() - 1);
            map.put("criticalid", String.valueOf(object.getArcId()));
            map.put("taptype", contentListRequest.getTapType());
        }
        if (contentListRequest.getSearchKey() != null) {
            map.put("searchkey", contentListRequest.getSearchKey());
        }
        map.put("cid", cid);
        WebUtils.showProgress = isShow;
        WebUtils.sendPost(getActivity(), "contentList", map, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                if (isSuccess) {
                    ContentListObject resultData = JSON.parseObject(data, ContentListObject.class);
                    datas.addAll(resultData.getList());
                    if (resultData.getList().size() == 0) {
                    } else {
                        if (adapter != null) {
                            dataHandler.sendEmptyMessage(0);
                        }
                    }
                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }

                recyclerview.hideHeaderView();
                recyclerview.hideFooterView();
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                recyclerview.hideHeaderView();
                recyclerview.hideFooterView();
            }
        });
    }

    public void downPullRefresh() {
        String url = "";
        if (datas.size() > 0) {
            ContentListObject.ListEntity object = datas.get(datas.size() - 1);
            url = "contentList.json?cid=" + cid + "&taptype=1" + "&criticalid=" +
                    String.valueOf(object.getArcId());
        }
        WebUtils.sendGet(getActivity(), url,new HashMap<String,Object>(), new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                String result = data;
                if (result != null && !result.equals("")) {
                    datas.clear();
                    ResultBaseModel baseModel = JSON.parseObject(
                            data, ResultBaseModel.class);
                    ContentListObject resultData = JSON.parseObject(baseModel.getData(), ContentListObject.class);
                    datas.addAll(resultData.getList());
                    adapter.notifyDataSetChanged();
                    recyclerview.hideHeaderView();
                } else {
                    Toast.makeText(getActivity(), "服务器出现故障", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                Toast.makeText(getActivity(), "刷新失败：" + msg, Toast.LENGTH_SHORT).show();
                recyclerview.hideHeaderView();
            }
        });
    }
}
